const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');

cloud.init({
    env: 'cloud1-9g2qt1ex40c305d9'
});

const db = cloud.database();
const _ = db.command;
const $ = _.aggregate;

const getParams = ctx => {
    let params = ctx._req.event;
    delete params.$url;
    return params;
}

const success = data => {
    return {
        status: 200,
        data
    }
}

const fail = data => {
    return {
        ...data
    }
}

exports.main = async (event, context) => {
    const app = new TcbRouter({ event });

    app.router('get_user_info', getUserInfo);
    app.router('save_config', saveConfig);
    app.router('get_guess_list', getGuessList);

    return app.serve();
}

// 获取用户信息
async function getUserInfo(ctx, next) {
    const wxContext = cloud.getWXContext()

    ctx.body = success({
        openid: wxContext.OPENID,
        appid: wxContext.APPID,
        unionid: wxContext.UNIONID,
    })
}

// 存储用户信息
async function saveConfig(ctx, next) {
    const wxContext = cloud.getWXContext();
    let { hostId, guestResult, guestAvatar, guestNickName, score } = getParams(ctx);
    let data = {
        hostId,
        guestId: wxContext.OPENID,
        guestResult,
        guestAvatar,
        guestNickName,
        score,
    }
    let result = await db.collection('questionUser').add({
        data: data
    })
    ctx.body = success({
        resList: result
    })
}

// 获取猜测列表
async function getGuessList(ctx, next) {
    const wxContext = cloud.getWXContext();
    let result = await db.collection('questionUser').where({
        hostId: wxContext.OPENID
    }).get()
    ctx.body = success({
        resultList: result.data
    })
}